package com.ruoyi.youtian.service.impl;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.gzmx_scdw.domain.Gzmx_scdw;
import com.ruoyi.gzmx_scdw.service.IGzmx_scdwService;
import com.ruoyi.youtian.domain.*;
import com.ruoyi.youtian.domain.vo.LinearGraphVo;
import com.ruoyi.youtian.domain.vo.PieChartVo;
import com.ruoyi.youtian.domain.vo.PointVo;
import com.ruoyi.youtian.mapper.PointAttributeMapper;
import com.ruoyi.youtian.mapper.PointEquipmentMapper;
import com.ruoyi.youtian.mapper.TWorkspaceCategoryMapper;
import com.ruoyi.youtian.mapper.TWorkspacePointMapper;
import com.ruoyi.youtian.service.ITWorkspaceCategoryService;
import lombok.Data;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 工作区分类Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-07
 */
@Service
public class TWorkspaceCategoryServiceImpl implements ITWorkspaceCategoryService
{
    @Autowired
    private TWorkspaceCategoryMapper tWorkspaceCategoryMapper;

    @Autowired
    private TWorkspacePointMapper tWorkspacePointMapper;

    @Autowired
    private PointAttributeMapper pointAttributeMapper;

    @Autowired
    private PointEquipmentMapper pointEquipmentMapper;


    @Autowired
    private IGzmx_scdwService igzmx_scdwService;
    /**
     * 查询工作区分类
     *
     * @param workspaceCategoryId 工作区分类主键
     * @return 工作区分类
     */
    @Override
    public TWorkspaceCategory selectTWorkspaceCategoryByWorkspaceCategoryId(Long workspaceCategoryId)
    {
        return tWorkspaceCategoryMapper.selectTWorkspaceCategoryByWorkspaceCategoryId(workspaceCategoryId);
    }

    /**
     * 查询工作区分类列表
     *
     * @param tWorkspaceCategory 工作区分类
     * @return 工作区分类
     */
    @DataScope(deptAlias = "d")
    @Override
    public List<TWorkspaceCategory> selectTWorkspaceCategoryList(TWorkspaceCategory tWorkspaceCategory)
    {
        return tWorkspaceCategoryMapper.selectTWorkspaceCategoryList(tWorkspaceCategory);
    }

    /**
     * 新增工作区分类
     *
     * @param tWorkspaceCategory 工作区分类
     * @return 结果
     */
    @Override
    public int insertTWorkspaceCategory(TWorkspaceCategory tWorkspaceCategory)
    {
        if(tWorkspaceCategory.getParentId() != 0){
            TWorkspaceCategory tWorkspaceCategory1 = tWorkspaceCategoryMapper.selectTWorkspaceCategoryByWorkspaceCategoryId(tWorkspaceCategory.getParentId());
            tWorkspaceCategory.setAncestors(tWorkspaceCategory1.getAncestors()+","+tWorkspaceCategory.getParentId());
        }else{
            tWorkspaceCategory.setAncestors("0");
        }
        tWorkspaceCategory.setCreateTime(DateUtils.getNowDate());
        return tWorkspaceCategoryMapper.insertTWorkspaceCategory(tWorkspaceCategory);
    }

    /**
     * 修改工作区分类
     *
     * @param tWorkspaceCategory 工作区分类
     * @return 结果
     */
    @Override
    public int updateTWorkspaceCategory(TWorkspaceCategory tWorkspaceCategory)
    {
        // 更新名称
        // 父级节点 不允许修改
        tWorkspaceCategory.setUpdateTime(DateUtils.getNowDate());
        return tWorkspaceCategoryMapper.updateTWorkspaceCategory(tWorkspaceCategory);
    }

    /**
     * 批量删除工作区分类
     *
     * @param workspaceCategoryIds 需要删除的工作区分类主键
     * @return 结果
     */
    @Override
    public int deleteTWorkspaceCategoryByWorkspaceCategoryIds(Long[] workspaceCategoryIds)
    {
        return tWorkspaceCategoryMapper.deleteTWorkspaceCategoryByWorkspaceCategoryIds(workspaceCategoryIds);
    }

    /**
     * 删除工作区分类信息
     *
     * @param workspaceCategoryId 工作区分类主键
     * @return 结果
     */
    @Override
    public int deleteTWorkspaceCategoryByWorkspaceCategoryId(Long workspaceCategoryId)
    {
        return tWorkspaceCategoryMapper.deleteTWorkspaceCategoryByWorkspaceCategoryId(workspaceCategoryId);
    }

    @Override
    public String checkTWorkspaceCategoryNameUnique(TWorkspaceCategory workspaceCategory) {
        List<TWorkspaceCategory> tWorkspaceCategories = tWorkspaceCategoryMapper.selectTWorkspaceCategoryList(workspaceCategory);
        if(tWorkspaceCategories != null && tWorkspaceCategories.size() > 0){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 查询站点树结构信息
     * @param tWorkspaceCategory 站点信息
     * @return
     */
    @Override
    public List<TWorkspaceCategoryTreeSelect> selectTWorkspaceCategoryTreeList(TWorkspaceCategory tWorkspaceCategory) {
        // 查询所有工作区
        List<TWorkspaceCategory> tWorkspaceCategories = this.selectTWorkspaceCategoryList(tWorkspaceCategory);
        // 构建工作区树
        List<TWorkspaceCategoryTreeSelect> treeSelects = buildTWorkspaceCategoryTreeSelect(tWorkspaceCategories);
        treeSelects.stream().forEach(select->{
            select.setChild(select.getChildren());
        });
        return treeSelects;
    }


    @Override
    public List<TWorkspaceCategoryTreeSelect> buildTWorkspaceCategoryTreeSelect(List<TWorkspaceCategory> tWorkspaceCategories) {
        List<TWorkspaceCategory> tWorkspaceCategoriesTrees = buildTWorkspaceCategoryTree(tWorkspaceCategories);
        return tWorkspaceCategoriesTrees.stream().map(TWorkspaceCategoryTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建树结构
     * @param tWorkspaceCategories  站点列表
     * @return
     */
    @Override
    public List<TWorkspaceCategory> buildTWorkspaceCategoryTree(List<TWorkspaceCategory> tWorkspaceCategories) {
        List<TWorkspaceCategory> returnList = new ArrayList<TWorkspaceCategory>();
        List<Long> tempList = new ArrayList<Long>();
        // 查询所有IDS
        for (TWorkspaceCategory tWorkspaceCategory : tWorkspaceCategories){
            tempList.add(tWorkspaceCategory.getWorkspaceCategoryId());
        }
        // 遍历查询所有ID
        for (TWorkspaceCategory tWorkspaceCategory : tWorkspaceCategories) {
            // 如果是顶级节点，遍历该父节点的所有子节点
            if (!tempList.contains(tWorkspaceCategory.getParentId())) {
                recursionFn(tWorkspaceCategories, tWorkspaceCategory);
                returnList.add(tWorkspaceCategory);
            }
        }
        if (returnList.isEmpty()) {
            returnList = tWorkspaceCategories;
        }
        return returnList;
    }

    @Override
    public boolean hasChildByWorkspaceCategoryId(Long workspaceCategoryId) {
        int result = tWorkspaceCategoryMapper.hasChildByWorkspaceCategoryId(workspaceCategoryId);
        return result > 0;
    }

    /**
     * 基础管理界面 为计量站添加采集点位，同时也添加点位属性值，场景ID默认为-1
     * @param tWorkspaceCategoryPointVo
     * @return
     */
    @Override
    public int insertPoint(TWorkspaceCategoryPointVo tWorkspaceCategoryPointVo) {
        TWorkspacePoint tWorkspacePoint = new TWorkspacePoint();
        tWorkspacePoint.setPointId(tWorkspaceCategoryPointVo.getPointId());
        tWorkspacePoint.setWorkspaceId(tWorkspaceCategoryPointVo.getWorkspaceCategoryId());
        tWorkspacePoint.setCreateBy(tWorkspaceCategoryPointVo.getCreateBy());
        tWorkspacePoint.setRemark(tWorkspaceCategoryPointVo.getRemark());
        tWorkspacePointMapper.insertTWorkspacePoint(tWorkspacePoint);
        PointAttribute pointAttribute = new PointAttribute();
        pointAttribute.setPointId(tWorkspaceCategoryPointVo.getPointId());
        pointAttribute.setSceneId(-1L);
        pointAttribute.setUpperLimit(tWorkspaceCategoryPointVo.getMaximum());
        pointAttribute.setLowerLimit(tWorkspaceCategoryPointVo.getMinimum());
        return pointAttributeMapper.insertPointAttribute(pointAttribute);
    }

    /**
     * 移除某工作区（workspaceCategoryId）下点位，并移除该点位下关联的设备和点位属性配置记录
     * @param tWorkspaceCategoryPointVo
     * @return
     */
    @Override
    public int deletePoint(TWorkspaceCategoryPointVo tWorkspaceCategoryPointVo) {
        // pointId
        PointEquipment pointEquipment = new PointEquipment();
        pointEquipment.setPointId(tWorkspaceCategoryPointVo.getPointId());
        pointEquipment.setUpdateBy(tWorkspaceCategoryPointVo.getUpdateBy());
        pointEquipmentMapper.detetePointEquipmentByPointEquipment(pointEquipment);
        // pointId
        PointAttribute pointAttribute = new PointAttribute();
        pointAttribute.setSceneId(-1L); // 删除默认采集点位上下限值
        pointAttribute.setPointId(tWorkspaceCategoryPointVo.getPointId());
        pointAttribute.setUpdateBy(tWorkspaceCategoryPointVo.getUpdateBy());
        pointAttributeMapper.deletePointAttributeByPointAttribute(pointAttribute);
        // 根据 pointId 和 workspaceCategoryId 确定一条记录
        TWorkspacePoint tWorkspacePoint = new TWorkspacePoint();
        tWorkspacePoint.setWorkspaceId(tWorkspaceCategoryPointVo.getWorkspaceCategoryId());
        tWorkspacePoint.setPointId(tWorkspaceCategoryPointVo.getPointId());
        tWorkspacePoint.setUpdateBy(tWorkspaceCategoryPointVo.getUpdateBy());
        return tWorkspacePointMapper.deleteTWorkspacePointByTWorkspacePoint(tWorkspacePoint);
    }

    /**
     * 递归集合列表往数据里面添加children
     */
    private void recursionFn(List<TWorkspaceCategory> list, TWorkspaceCategory tWorkspaceCategory)
    {
        // 得到子节点列表
        List<TWorkspaceCategory> childList = getChildList(list, tWorkspaceCategory);
        tWorkspaceCategory.setChildren(childList);
        for (TWorkspaceCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<TWorkspaceCategory> getChildList(List<TWorkspaceCategory> list, TWorkspaceCategory tWorkspaceCategory)
    {
        List<TWorkspaceCategory> tlist = new ArrayList<TWorkspaceCategory>();
        Iterator<TWorkspaceCategory> it = list.iterator();
        while (it.hasNext())
        {
            TWorkspaceCategory n = (TWorkspaceCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == tWorkspaceCategory.getWorkspaceCategoryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TWorkspaceCategory> list, TWorkspaceCategory t)
    {
        return getChildList(list, t).size() > 0;
    }


    /**
     *  查询当前节点下所有子集Id
     * @param  tWorkspaceCategoryPointVo
     * @return
     */
//    @DataScope(deptAlias = "d")
    @Override
    public List<Long>  findChildIdList(TWorkspaceCategoryPointVo tWorkspaceCategoryPointVo){
        List<Long>  idList = new ArrayList<>();
        Long id = tWorkspaceCategoryPointVo.getWorkspaceCategoryId();
        idList.add(id);
        // 查询所有工作区
        TWorkspaceCategory bean =  new TWorkspaceCategory();
        List<TWorkspaceCategory> tWorkspaceCategories = this.selectTWorkspaceCategoryList(bean);
        //  查询所有子节点
        List<TWorkspaceCategory> tWorkspaceCategoriesList = buildTWorkspaceCategoryTree(tWorkspaceCategories);
        for (TWorkspaceCategory tWorkspaceCategory : tWorkspaceCategoriesList) {
            if(tWorkspaceCategory.getWorkspaceCategoryId() == id){
                idList.addAll(findChildWorkspaceCategoryIdList(tWorkspaceCategory.getChildren()));
            }
        }
        return idList;
    }

    @Override
    public List<PointVo> selectDevicePointList(PointVo pointVo) {
        return tWorkspaceCategoryMapper.selectDevicePointList(pointVo);
    }

    public List<PointVo>  selectPointListByWorkspaceIdList(List<Long> childIdList, String pointName){
        TWorkspaceCategory tWorkspaceCategory = new TWorkspaceCategory();
        return  this.tWorkspaceCategoryMapper.selectPointListByWorkspaceIdList(childIdList, pointName, tWorkspaceCategory);
    }

    private List<Long> findChildWorkspaceCategoryIdList(List<TWorkspaceCategory> tWorkspaceCategories1){
        List<Long> list = new ArrayList<>();
        Iterator<TWorkspaceCategory> it = tWorkspaceCategories1.iterator();
        while (it.hasNext())
        {
            TWorkspaceCategory n = (TWorkspaceCategory) it.next();
            list.add(n.getWorkspaceCategoryId());
            if(n.getChildren().size() > 0){
                findChildWorkspaceCategoryIdList(n.getChildren());
            }
        }
        return list;
    }

    /**
     * 线状图
     * @param linearGraphVo
     * @return
     */
    @Override
    public AjaxResult getLineargraph(LinearGraphVo linearGraphVo) {
        return AjaxResult.success(tWorkspaceCategoryMapper.getLineargraph(linearGraphVo));
    }

    @Override
    public AjaxResult getPieChart(PieChartVo pieChartVo ) {
        List<HashMap> hashMaps = new ArrayList<>();
        List<Map<String, Object>> mapList = tWorkspaceCategoryMapper.getPieChart(pieChartVo);
        mapList.forEach(sum ->{
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("police",sum.get("police"));
            hashMap.put("pointsum",sum.get("pointsum"));
            hashMap.put("name",pieChartVo.getSceneName());
            hashMaps.add(hashMap);
        });

        return AjaxResult.success(hashMaps);
    }

    @Override
    public AjaxResult getColumndiagram(PieChartVo pieChartVo) {
        List<HashMap> hashMaps = new ArrayList<>();
        List<PieChartVo> list = tWorkspaceCategoryMapper.selectcategory(null);
        for (PieChartVo chartVo : list) {
            if (pieChartVo.getScene_id()!=null || pieChartVo.getDw_3_id() != null||pieChartVo.getEjdw_id()!=null||pieChartVo.getZyq_id()!=null) {
                if (pieChartVo.getScene_id()!=null)
                chartVo.setScene_id(pieChartVo.getScene_id());
                List<PieChartVo> name = tWorkspaceCategoryMapper.selectcategory(chartVo.getScene_id());
                if (pieChartVo.getDw_3_id() != null)
                chartVo.setDw_3_id(pieChartVo.getDw_3_id());
                if (pieChartVo.getEjdw_id()!=null)
                chartVo.setEjdw_id(pieChartVo.getEjdw_id());
                if (pieChartVo.getZyq_id()!=null)
                chartVo.setZyq_id(pieChartVo.getZyq_id());
                List<Map<String, Object>> chart = tWorkspaceCategoryMapper.getPieChart(chartVo);
                chart.forEach(suo->{
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("name",name.get(0).getSceneName());
                    hashMap.put("police",suo.get("police"));
                    hashMap.put("pointsum",suo.get("pointsum"));
                    hashMaps.add(hashMap);
                });
                List<PieChartVo> pinjie = tWorkspaceCategoryMapper.selectcategory(null);
                for (int i = 0; i < list.size() - chart.size(); i++) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("name",pinjie.get(i).getSceneName());
                    hashMap.put("police",0);
                    hashMap.put("pointsum",0);
                    hashMaps.add(hashMap);
                }
                return AjaxResult.success(hashMaps);
            }
            List<Map<String, Object>> chart = tWorkspaceCategoryMapper.getPieChart(chartVo);
            chart.forEach(suo->{
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("name",chartVo.getSceneName());
                hashMap.put("police",suo.get("police"));
                hashMap.put("pointsum",suo.get("pointsum"));
                hashMaps.add(hashMap);
            });
        }
        return AjaxResult.success(hashMaps);
    }
}
